package cn.bugDance.trigger.listener;

import cn.bugDance.domain.activity.model.entity.DeliverOrderEntity;
import cn.bugDance.domain.activity.service.quota.IRaffleActivityQuotaService;
import cn.bugDance.domain.credit.model.valobj.CreditPayVO;
import cn.bugDance.types.exception.AppException;
import cn.bugDance.types.response.BaseEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
@RocketMQMessageListener(topic = "creditPayTopic", consumerGroup = "credit-consumer-group")
public class CreditPaySuccessListener implements RocketMQListener<String> {

    @Resource
    private IRaffleActivityQuotaService raffleActivityQuotaService;

    @Override
    public void onMessage(String s) {
        try{
            BaseEvent<CreditPayVO> message = JSON.parseObject(s, new TypeReference<BaseEvent<CreditPayVO>>(){});
            if(null == message) return;
            String userId = message.getData().getUserId();
            String outBusinessId = message.getData().getOutBusinessId();

            log.info("【CreditPaySuccessListener->】积分交易MQ消费者接收到变更消息, userId: {}", userId);
            DeliverOrderEntity deliverOrderEntity = new DeliverOrderEntity();
            deliverOrderEntity.setUserId(userId);
            deliverOrderEntity.setOutBusinessNo(outBusinessId);

            raffleActivityQuotaService.updateCreditPayOrder(deliverOrderEntity);
        }catch (AppException e){
            log.warn("【CreditPaySuccessListener->】mysql唯一索引冲突");
            return;
        }catch (Exception e){
            log.warn("【CreditPaySuccessListener->】积分交易消费者出现异常, msg: {}", e.getMessage());
            throw e;
        }

    }
}
